import {
  ChatMessage,
  ChatCompletionRequest,
  ChatCompletionResponse,
  ChatCompletionStreamResponse,
  SqlQueryRequest,
  SqlQueryResponse,
  HealthCheckResponse,
  ApiErrorResponse
} from './types';

// API客户端 - 不依赖LangGraph组件

export class ApiClient {
  private baseUrl: string;
  private headers: Record<string, string>;

  constructor(baseUrl: string = 'http://localhost:8013') {
    this.baseUrl = baseUrl;
    this.headers = {
      "Content-Type": "application/json",
    };
  }

  // 健康检查
  async healthCheck(): Promise<HealthCheckResponse> {
    const response = await fetch(`${this.baseUrl}/health`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    });
    
    if (!response.ok) {
      throw new Error(`Health check failed: ${response.statusText}`);
    }
    
    return response.json();
  }

  // 聊天完成接口
  async chatCompletions(
    request: ChatCompletionRequest,
  ): Promise<ChatCompletionResponse> {
    const response = await fetch(`${this.baseUrl}/v1/chat/completions`, {
      method: "POST",
      headers: this.headers,
      body: JSON.stringify(request),
    });

    if (!response.ok) {
      throw new Error(`Chat completion failed: ${response.statusText}`);
    }

    return response.json();
  }

  // 流式聊天完成
  async *chatCompletionsStream(
    request: ChatCompletionRequest,
  ): AsyncGenerator<string, void, unknown> {
    const streamRequest = { ...request, stream: true };

    const response = await fetch(`${this.baseUrl}/v1/chat/completions`, {
      method: "POST",
      headers: this.headers,
      body: JSON.stringify(streamRequest),
    });

    if (!response.ok) {
      throw new Error(`Stream chat completion failed: ${response.statusText}`);
    }

    const reader = response.body?.getReader();
    if (!reader) {
      throw new Error("No response body reader available");
    }

    const decoder = new TextDecoder();
    let buffer = "";

    try {
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        buffer += decoder.decode(value, { stream: true });
        const lines = buffer.split("\n");
        buffer = lines.pop() || "";

        for (const line of lines) {
          if (line.startsWith("data: ")) {
            const data = line.slice(6).trim();
            if (data === "[DONE]") {
              return;
            }
            try {
              const parsed = JSON.parse(data);
              const content = parsed.choices?.[0]?.delta?.content;
              if (content) {
                yield content;
              }
            } catch (e) {
              console.warn("Failed to parse SSE data:", data);
            }
          }
        }
      }
    } finally {
      reader.releaseLock();
    }
  }

  // SQL查询接口
  async sqlQuery(request: SqlQueryRequest): Promise<SqlQueryResponse> {
    const response = await fetch(`${this.baseUrl}/sql/query`, {
      method: "POST",
      headers: this.headers,
      body: JSON.stringify(request),
    });

    if (!response.ok) {
      throw new Error(`SQL query failed: ${response.statusText}`);
    }

    return response.json();
  }

  // SQL健康检查
  async sqlHealthCheck(): Promise<HealthCheckResponse> {
    const response = await fetch(`${this.baseUrl}/sql/health`);
    if (!response.ok) {
      throw new Error(`SQL health check failed: ${response.statusText}`);
    }
    return response.json();
  }
}

// 创建默认客户端实例
export const apiClient = new ApiClient(process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8013');
